<?php


namespace app\common\controller;


use app\common\job\SendNotify;
use app\common\model\Agent;
use app\common\model\AgentApply;
use app\common\model\CardGeneral;
use app\common\model\CardMember;
use app\common\model\CardUserGet;
use app\common\model\Paylog;

class CreateNotify
{
    //领卡事件处理完后调用此方法完成向第三方平台的推送
    public function card_rec_notify($param){
        try {
            $CardMember = new CardMember();
            $cardinfo = $CardMember->where(['card_id'=>$param['CardId']])->field('id,mid')->find();
            $notify_param['notify_category'] = "card_rec";
            $notify_param['merchantid']=$cardinfo['mid'];
            //END
            $notify_param['card_id'] = !empty($param['CardId'])?$param['CardId']:"";      //card_id
            $notify_param['code'] = !empty($param['UserCardCode'])?$param['UserCardCode']:"";          //code
            $notify_param['openid'] = !empty($param['FromUserName'])?$param['FromUserName']:"";        //所有人openid
            $notify_param['unionid'] =  !empty($param['UnionId'])?$param['UnionId']:"";     //所有人unionid
            $notify_param['create_time'] =  !empty($param['CreateTime'])?$param['CreateTime']:time();    //领卡时间
            $notify_param['outer_str'] = !empty($param['OuterStr'])?$param['OuterStr']:"";    //领卡渠道
            $notify_param['source_scene'] = !empty($param['SourceScene'])?$param['SourceScene']:"";;  //领卡场景
            //END
            //拓展字段   可不填
//        $notify_param['name'] = "";         //领卡人姓名
//        $notify_param['phone'] = "";        //领卡人电话
//        $notify_param['address'] = "";      //领卡人地址
//        $notify_param['email'] = "";        //领卡人邮箱
            //END
            $ActionLogs = new ActionLogs();
            $ActionLogs->writelog("payos", "createnotify", "notify/cardrec", "PUB:", $notify_param);

            $SendNotify=new SendNotify();
            $res = $SendNotify->task_biz_notify($notify_param);
            $ActionLogs->writelog("payos", "createnotify", "notify/cardrec", "RES:", $res);
        } catch (\Exception $e) {
            $ActionLogs = new ActionLogs();
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            $ActionLogs->writelog("payos", "createnotify", "notify/cardrec", "ERROR:", $data2);
        }
    }

    //领卡事件处理完后调用此方法完成向第三方平台的推送
    public function quan_rec_notify($param){
        try {
            $CardGeneral = new CardGeneral();
            $cardinfo = $CardGeneral->where(['card_id'=>$param['CardId']])->field('id,mid')->find();
            $notify_param['notify_category'] = "quan_rec";
            $notify_param['merchantid']=$cardinfo['mid'];
            //END
            $notify_param['card_id'] = !empty($param['CardId'])?$param['CardId']:"";      //card_id
            $notify_param['code'] = !empty($param['UserCardCode'])?$param['UserCardCode']:"";          //code
            $notify_param['openid'] =  !empty($param['FromUserName'])?$param['FromUserName']:"";        //所有人openid
            $notify_param['unionid'] =  !empty($param['UnionId'])?$param['UnionId']:"";     //所有人unionid
            $notify_param['create_time'] =  !empty($param['CreateTime'])?$param['CreateTime']:time();    //领卡时间
            $notify_param['outer_str'] = !empty($param['OuterStr'])?$param['OuterStr']:"";    //领卡渠道
            $notify_param['source_scene'] = !empty($param['SourceScene'])?$param['SourceScene']:"";;  //领卡场景
            //END
            $ActionLogs = new ActionLogs();
            $ActionLogs->writelog("payos", "createnotify", "notify/quanrec", "rec:", $notify_param);
            //END
            $SendNotify=new SendNotify();
            $SendNotify->task_biz_notify($notify_param);
        } catch (\Exception $e) {
            $ActionLogs = new ActionLogs();
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            $ActionLogs->writelog("payos", "createnotify", "notify/quanrec", "ERROR:", $data2);
        }
    }

    //用户删卡/删券事件处理完后调用此方法完成向第三方平台的推送
    public function cards_del_notify($param){
        try {
            $CardUserGet = new CardUserGet();
            $map['openid'] = !empty($param['openid'])?$param['openid']:"";
            $map['card_id'] = !empty($param['card_id'])?$param['card_id']:"";
            $map['code'] = !empty($param['code'])?$param['code']:"";
            $codeinfo = $CardUserGet->where($map)->field('card_type,mid,top_mid,unionid')->find();
            //END
            $notify_param['notify_category'] = "cards_del";
            $notify_param['merchantid']=$codeinfo['mid'];
            //END
            $notify_param['card_type'] = $codeinfo['card_type'];      //card_type
            $notify_param['unionid'] = $codeinfo['unionid'];     //所有人unionid
            $notify_param['card_id'] = !empty($param['card_id'])?$param['card_id']:"";
            $notify_param['code'] = $param['code'];          //code
            $notify_param['openid'] =  $param['openid'];        //所有人openid
            $notify_param['create_time'] =  $param['create_time'];    //领卡时间
            //END
            $SendNotify=new SendNotify();
            $SendNotify->task_biz_notify($notify_param);
        } catch (\Exception $e) {
            $ActionLogs = new ActionLogs();
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            $ActionLogs->writelog("payos", "createnotify", "notify/del", "ERROR:", $data2);
        };
    }

    //消券事件处理完后调用此方法完成向第三方平台的推送
    //传入核销记录数据

    public function quan_con_notify($param){
        try {
            $notify_param['notify_category'] = "quan_con";
            $notify_param['merchantid']=$param['mid'];
            //END
            $notify_param['card_id'] = $param['card_id'];      //card_id
            $notify_param['code'] = $param['code'];          //code
            $notify_param['openid'] =  $param['openid'];        //所有人openid
            $notify_param['unionid'] =  !empty($param['unionid'])?$param['unionid']:"";     //所有人unionid
            $notify_param['create_time'] =  $param['create_time'];    //领卡时间
            $notify_param['consume_source'] = $param['source'];                      //核销来源
            $notify_param['mach_name'] = !empty($param['mach_name'])?$param['mach_name']:"";;             //商户名称
            $notify_param['staff_name'] = $param['action_user'];            //操作人名称
            $notify_param['verify_code'] = "";           //核销验证码
            $notify_param['remark'] = "";                //核销备注
            $notify_param['outerstr'] = $param['kuantai'];              //款台
            //END
            $SendNotify=new SendNotify();
            $SendNotify->task_biz_notify($notify_param);
        } catch (\Exception $e) {
            $ActionLogs = new ActionLogs();
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            $ActionLogs->writelog("payos", "createnotify", "notify/del", "ERROR:", $data2);
        };
    }

    public function pay_notify($param)
    {
        try {
            $Paylog = new Paylog();
            $payinfo = $Paylog->where('orderid', $param['out_trade_no'])->find();
            if ($payinfo['pay_statu'] == 1) {
                if (!empty($payinfo['cashier'])) {
                    $device_id = $payinfo['cashier'];

                } elseif (!empty($payinfo['d_cashier'])) {
                    $device_id = $payinfo['d_cashier'];

                } else {
                    $device_id = "";
                }
                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "SUCCESS";
                $arrc['return_msg'] = "支付成功";
                $arrc['result_msg'] = "支付成功";
                $arrc['notify_category'] = "pay";
                $arrc['out_trade_no'] = $payinfo['orderid'];
                $arrc['trade_no'] = $payinfo['trade_no'];
                $arrc['order_no'] = $payinfo['orderno'];
                $arrc['total_fee'] = $payinfo['price'];//实付金额
                $arrc['channel'] = $payinfo['pay_fs'];//实付金额
                $arrc['merchantname'] = getmerchant($payinfo['mid']);//商户名称
                $arrc['ought_fee'] = $payinfo['yf_price'];//应付金额
                $arrc['gel_fee'] = $payinfo['zk_price'];//折扣金额
                $arrc['dis_card_zk'] = $payinfo['dis_card_zk'];        //会员卡折扣     field('dis_card_zk,vip_card_zk,gel_card_zk,hx_card')->
                $arrc['vip_card_zk'] = $payinfo['vip_card_zk'];        //等级折扣
                $arrc['gel_card_zk'] = $payinfo['gel_card_zk'];        //卡券抵扣
                $arrc['service_charge'] = $payinfo['service_charge'];        //手续费
                $arrc['end_time'] = !empty($payinfo['pay_time']) ? $payinfo['pay_time'] : "";//支付时间
                $arrc['gel_info'] = $this->getdeduzkinfo($payinfo['hx_card'], $payinfo['gel_card_zk']);        //抵扣明细
                $arrc['openid'] = $payinfo['openid'];       //抵扣明细
                $arrc['sub_openid'] = $payinfo['sub_openid'];       //抵扣明细
                $arrc['attach'] = $payinfo['attach'];       //抵扣明细
                $arrc['device_id'] = $device_id;     //收银员
                $arrc['merchantid'] = $param['merchantid'];
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '支付成功';
                $SendNotify = new SendNotify();
                $s = $SendNotify->task_biz_notify($arrc);


            }
        } catch (\Exception $e) {
            file_put_contents('/data2/html/yuanqu/syncnotify3.log', "[" . date('Y-m-d H:i:s') . "]" . ":" . $e->getMessage() . PHP_EOL, 8);

        }

    }

    private function getdeduzkinfo($arr, $card_zk)
    {
        $arr = json_decode($arr, true);
        $CardGeneral = new \app\common\model\CardGeneral();
        if (is_array($arr)) {
            foreach ($arr as $k => $v) {
                if (isset($v['card_id'])) {
                    $datas[$k] = $CardGeneral->where(['card_id' => $v['card_id']])->value('title');
                } else {
                    $datas = [];
                }
            }
        } else {
            $datas = [];
        }

        if ($datas) {
            $data = implode(',', $datas) . '(' . $card_zk . '元)';
        } else {
            $data = NULL;
        }
        return $data;
    }

    //代理商审核完成后通知
    public function appoval_agent_notify($param){
//        try {
        $s = 123;
        if ($param['appoval_status'] == "N") {
            $AgentApply = new AgentApply();
            $info = $AgentApply->where(['id' => $param['agentid']])->find();

        }else{
            $Agent = new Agent();
            $info = $Agent->where(['id' => $param['agentid']])->find();

        }
        if($info) {
            $notify_param['notify_category'] = "agent_apply_appoval";
            $notify_param['agentid'] = $param['agentid'];
            $notify_param['wn_cardus_appid'] = $info['sign_appid'];      //card_id
            $notify_param['wn_cardus_appkey'] = $info['sign_key'];      //card_id
            $notify_param['appoval_status'] = $param['appoval_status'];      //card_id
            $notify_param['appoval_remark'] = $param['appoval_remark'];      //card_id
            $notify_param['bus_no'] = $param['bus_no'];      //card_id
            //END
            $ApiHttpCommon = new ApiHttpCommon();
            if (!empty($info['notify_url'])) {
                $notify_url = $info['notify_url'];
                $data = json_encode($notify_param, JSON_UNESCAPED_UNICODE);
                $s = $ApiHttpCommon->http_post($notify_url, $data);
            }
        }
        return $s;
//        } catch (\Exception $e) {
//            $ActionLogs = new ActionLogs();
//            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            trace("代理商审核通知错误：" . json_encode($param, 256), 'SysRunErrorLog');
//        };
    }

}